package StudyCode.summary.BufferAndChannel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class WriteCharacterSeekableByteChannel {
	public static void main(String[] args) {

		Path path = Paths.get("E:\\Copy", "1.txt");
		ByteBuffer buffer_1 = ByteBuffer.wrap("写入测试.".getBytes());
		ByteBuffer buffer_2 = ByteBuffer.wrap("666".getBytes());
		try (SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path,
				EnumSet.of(StandardOpenOption.WRITE)))) {
			seekableByteChannel.position(seekableByteChannel.size());
			while (buffer_1.hasRemaining()) {
				seekableByteChannel.write(buffer_1);
			}
			seekableByteChannel.position(301);
			while (buffer_2.hasRemaining()) {
				seekableByteChannel.write(buffer_2);
			}
			buffer_1.clear();
			buffer_2.clear();
			System.out.println("写入成功");
		} catch (IOException ex) {
			System.err.println(ex);
		}
	}
}
